<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="预落时间" prop="preLandingTime">
        <el-input
          v-model="queryParams.preLandingTime"
          placeholder="请输入预落时间(HHmm)"
          clearable
          @input="handleTimeInput('preLandingTime', $event)"
          @blur="handleTimeBlur('preLandingTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="实落时间" prop="inboundTime">
        <el-input
          v-model="queryParams.inboundTime"
          placeholder="请输入实落时间(HHmm)"
          clearable
          @input="handleTimeInput('inboundTime', $event)"
          @blur="handleTimeBlur('inboundTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button @click="openCanleInfo"><Icon icon="ep:plus" class="mr-5px" /> 取消航班统计</el-button>
        <el-button type="primary" plain @click="handleOpenColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="height: 62vh">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
            @row-dblclick="handleRowDblClick"
            :row-class="tableRowClassName"
          />
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>

  <!-- 列设置弹窗 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="mb-4 flex justify-between items-center">
      <span>拖拽调整列顺序</span>
    </div>

    <div style="text-align: center">
      <el-transfer
        v-model="tempSelectedColumnProps"
        :data="allColumnsForTransfer"
        filterable
        :titles="['可选列', '已选列']"
        :button-texts="['移除', '选中']"
        class="mb-4"
      />
    </div>

    <div v-if="tempSelectedColumns.length > 0">
      <el-card>
        <template #header>已选列顺序</template>
        <div class="draggable-list">
          <div
            v-for="(column, index) in tempSelectedColumns"
            :key="column.prop"
            class="draggable-item flex items-center justify-between p-3 border rounded-lg cursor-move bg-white transition-all duration-200 hover:shadow-md"
            @mousedown="startDrag(index, $event)"
            :style="{
              transform: isDragging && dragIndex === index ? 'scale(1.02)' : 'none',
              opacity: isDragging ? (dragIndex === index ? '0.8' : '0.5') : '1',
              'background-color': isDragging && dragOverIndex === index ? '#f0f7ff' : 'white',
              'border-color': isDragging && dragOverIndex === index ? '#409eff' : '#dcdfe6'
            }"
          >
            <div class="flex items-center space-x-3">
              <el-icon
                class="el-icon-rank text-gray-400 cursor-move hover:text-blue-500 transition-colors"
              >
                <Rank />
              </el-icon>
              <span class="font-medium">{{ column.label }}</span>
            </div>

            <div class="flex items-center space-x-2">
              <el-tooltip :content="`列宽度: ${column.width || 150}px`" placement="top">
                <el-icon class="text-gray-400 hover:text-blue-500 cursor-pointer transition-colors">
                  <Monitor />
                </el-icon>
              </el-tooltip>

              <el-tooltip :content="`类型: ${column.type || '文本'}`" placement="top">
                <el-icon
                  class="text-gray-400 hover:text-green-500 cursor-pointer transition-colors"
                >
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 餐食信息弹窗 -->
  <el-dialog title="餐食信息" v-model="recipeVisible" width="600px" :close-on-click-modal="false">
    <el-table :data="recipeInfosList">
      <el-table-column label="舱位" align="center" prop="cabinClass" min-width="120" />
      <el-table-column label="餐谱" align="center" prop="recipeName" min-width="120" />
      <el-table-column label="数量" align="center" prop="recipeQty" min-width="120" />
    </el-table>
  </el-dialog>

  <!-- 排班信息弹窗 -->
  <el-dialog title="排班信息" v-model="shitfVisible" width="800px" :close-on-click-modal="false">
    <el-table :data="shiftInfosList">
      <el-table-column label="排班编号" align="center" prop="shiftCode" min-width="120" />
      <el-table-column label="排班时间" align="center" prop="shiftTime" min-width="120" />
      <el-table-column label="司机" align="center" prop="shiftDriverName" min-width="120" />
      <el-table-column label="保障员" align="center" prop="shiftSupportName" min-width="120" />
      <el-table-column label="航机员" align="center" prop="shiftCrewName" min-width="120" />
      <el-table-column label="车辆信息" align="center" prop="carInfo" min-width="120" />
    </el-table>
  </el-dialog>

  <!-- 取消航班统计信息弹窗 -->
  <el-dialog title="统计取消航班信息" v-model="cancleVisible" width="800px" :close-on-click-modal="false">
    <span>取消航班： {{cancleRecordsList.length}} 架次</span>
    <el-table :data="cancleRecordsList">
      <el-table-column label="航班号" align="center" prop="flightNo" min-width="120" />
      <el-table-column label="日期" align="center" prop="recordDate" min-width="120" />
    </el-table>
  </el-dialog>

  <!-- 加餐表单 -->
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted, computed, nextTick, watch, onUnmounted, h } from 'vue'
import {
  ElInput,
  ElButton,
  ElTag,
  ElTooltip,
  ElIcon,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem
} from 'element-plus'
import {
  Rank,
  Monitor,
  InfoFilled,
  Search,
  Refresh,
  Setting,
  DArrowRight,
  Plus
} from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
import { DICT_TYPE } from '@/utils/dict'
import { ProduceRecordApi } from '@/api/pplan/producerecord'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'

/** 基础配置 */
defineOptions({ name: 'ScheduleRecordShift' })
const message = useMessage()
const { t } = useI18n()

const TABLE_TYPE = 'shift'

// 生产状态列表
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

const formAddRef = ref()

// 状态管理
const loading = ref(true)
const list = ref<ScheduleRecordVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined
})
const queryFormRef = ref()

/** 业务逻辑 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getIngScheduleRecordPage(queryParams)
    list.value = data.list || []
    list.value.forEach((item) => {
      item.original = JSON.parse(JSON.stringify(item))
      // 时间格式化
      item.inboundTime = normalizeTimeFormat(item.inboundTime)
      item.preLandingTime = normalizeTimeFormat(item.preLandingTime)
      item.depTime = normalizeTimeFormat(item.depTime)

      // 修复1：确保pstatus为数字类型，处理接口返回可能的字符串或空值
      item.pstatus = item.pstatus !== undefined && item.pstatus !== null ? Number(item.pstatus) : 0

      // 保存格式化原始值
      item.formattedOriginal = {
        inboundTime: item.inboundTime || '',
        preLandingTime: item.preLandingTime || '',
        depTime: item.depTime || '',
        machineNo: item.machineNo || '',
        airportStands: item.airportStands || '',
        bussClassQty: item.bussClassQty || '',
        premEcoClassQty: item.premEcoClassQty || '',
        ecoClassQty: item.ecoClassQty || '',
        carInfo: item.carInfo || '',
        pstatus: item.pstatus // 保存处理后的pstatus值
      }
    })
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const normalizeTimeFormat = (timeValue: any): string => {
  if (!timeValue) return ''
  if (Array.isArray(timeValue) && timeValue.length === 2) {
    const hour = String(timeValue[0]).padStart(2, '0')
    const minute = String(timeValue[1]).padStart(2, '0')
    return `${hour}:${minute}`
  }
  if (typeof timeValue === 'string') {
    if (/^\d{2}:\d{2}$/.test(timeValue)) return timeValue
    if (/^\d{4}$/.test(timeValue)) return `${timeValue.slice(0, 2)}:${timeValue.slice(2, 4)}`
  }
  return ''
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const getUserList = async () => {
  try {
    const shiftDate = formatDate(new Date(), 'YYYY-MM-DD')
    const data = await ShiftRecordApi.getShiftRecordSimple(shiftDate)
    userList.value = data || []
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

const othUserList = ref([])
const getOthUserList = async () => {
  try {
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    const othShiftDate = formatDate(tomorrow, 'YYYY-MM-DD')
    const data = await ShiftRecordApi.getShiftRecordSimple(othShiftDate)
    othUserList.value = data || []
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

const handleFieldChange = async (row: ScheduleRecordVO, field?: string) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }
    const hasChange = Object.keys(row).some((key) => {
      if (key === 'original' || key === 'formattedOriginal') return false
      const originalVal = row.formattedOriginal[key] || ''
      const currentVal = row[key] || ''
      if (isTimeColumn(key)) return originalVal !== currentVal
      if (isNumberColumn(key)) return String(originalVal) !== String(currentVal)
      return originalVal !== currentVal
    })
    if (!hasChange) return

    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO

    await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(t('修改信息成功'))
    row.original = JSON.parse(JSON.stringify(row))
    row.formattedOriginal = {
      inboundTime: row.inboundTime || '',
      preLandingTime: row.preLandingTime || '',
      depTime: row.depTime || '',
      machineNo: row.machineNo || '',
      airportStands: row.airportStands || '',
      bussClassQty: row.bussClassQty || '',
      premEcoClassQty: row.premEcoClassQty || '',
      ecoClassQty: row.ecoClassQty || '',
      carInfo: row.carInfo || '',
      pstatus: row.pstatus || 0
    }
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('字段更新失败:', err)
    await getList()
  }
}

const handleCarInfoBlur = async (row: ScheduleRecordVO) => {
  const currentVal = row.carInfo || ''
  const originalVal = row.formattedOriginal.carInfo || ''
  if (currentVal === originalVal) return
  try {
    await ScheduleRecordApi.updateScheduleRecordShift(row)
    message.success(t('修改排班信息成功'))
    row.original.carInfo = row.carInfo
    row.formattedOriginal.carInfo = currentVal
  } catch (err) {
    await getList()
  }
}

const handleRowDblClick = (row: ScheduleRecordVO) => {
  openShiftInfo(row.carInfo, row.recordDate)
}

// 排班信息弹窗
const shitfVisible = ref(false)
const shiftInfosList = ref([])
const openShiftInfo = (carInfo: string, shiftDate: string) => {
  if (carInfo && shiftDate) {
    ShiftRecordApi.getShiftRecordSimple(carInfo, shiftDate)
      .then((result) => {
        shiftInfosList.value = result || []
        shitfVisible.value = true
      })
      .catch(() => message.error('获取排班信息失败'))
  } else {
    message.warning('请先输入排班编号')
  }
}

// 排班信息弹窗
const cancleVisible = ref(false)
const cancleRecordsList = ref([])
const openCanleInfo = () => {
  ScheduleRecordApi.getCancleScheduleRecordPage()
      .then((result) => {
        cancleRecordsList.value = result || []
        cancleVisible.value = true
      })
      .catch(() => message.error('统计取消航班信息失败'))
}

/** 生产状态切换方法 */
const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    if (row.pstatus === newStatus) return
    const updateData = { id: row.id, pstatus: newStatus } as Partial<ScheduleRecordVO>
    await ScheduleRecordApi.updateScheduleRecord(updateData)
    // 修复2：更新后直接赋值确保即时回显
    row.pstatus = newStatus
    row.formattedOriginal.pstatus = newStatus
    message.success(t('common.updateSuccess'))
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('生产状态更新失败：', err)
    await getList()
  }
}

/** 加餐表单打开方法 */
const openAddForm = (flightNo?: string, recordDate?: string) => {
  formAddRef.value?.openAdd('create', flightNo, recordDate)
}

/** 时间输入处理 */
const handleTimeInput = (field: string, value: string) => {
  queryParams[field] = value.replace(/[^0-9]/g, '')
}

const handleTimeBlur = (field: string) => {
  const value = queryParams[field]
  if (!value) return
  if (/^\d{2}:\d{2}$/.test(value)) return
  if (value.length !== 4 || !/^\d{4}$/.test(value)) {
    message.error('请输入4位数字的时间格式(HHmm)')
    queryParams[field] = ''
    return
  }
  const formatted = formatTimeString(value)
  queryParams[field] = formatted || ''
  if (!formatted) message.error('请输入有效的时间格式(HHmm)')
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

const isNumberColumn = (prop: string): boolean => {
  return ['bussClassQty', 'premEcoClassQty', 'ecoClassQty'].includes(prop)
}

const formatDisplayTime = (timeString: string | undefined): string | null => {
  return timeString ? formatTimeString(timeString) : null
}

const formatTimeString = (timeString: string): string | null => {
  if (timeString.includes(':')) return timeString
  if (!/^\d{4}$/.test(timeString)) return null
  const hours = parseInt(timeString.slice(0, 2))
  const minutes = parseInt(timeString.slice(2, 4))
  return hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60
    ? `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
    : null
}

const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleColumnTimeBlur = async (row: any, prop: string) => {
  const value = row[prop]
  const original = row.formattedOriginal[prop] || ''
  const current = value || ''
  if (current === original) return

  if (current && /^\d{2}:\d{2}$/.test(current)) {
    await handleFieldChange(row)
    return
  }

  if (current && (current.length !== 4 || !/^\d{4}$/.test(current))) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`)
    row[prop] = original
    return
  }

  if (current) {
    const formatted = formatTimeString(current)
    if (formatted) {
      row[prop] = formatted
      await handleFieldChange(row)
    } else {
      message.error('请输入有效的时间格式(HHmm)')
      row[prop] = original
    }
  } else {
    await handleFieldChange(row)
  }
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleNumberBlur = async (row: any, prop: string) => {
  const value = row[prop]
  const original = row.formattedOriginal[prop] || ''
  const current = value || ''
  if (String(current) === String(original)) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) < 0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  const value = row[prop]
  const original = row.formattedOriginal[prop] || ''
  const current = value || ''
  if (current === original) return
  await handleFieldChange(row)
}

const getColumnNameByProp = (prop: string): string => {
  const column = allColumns.find((col) => col.prop === prop)
  return column?.label || prop
}

// 餐食信息弹窗
const recipeVisible = ref(false)
const recipeInfosList = ref([])
const openRecipeInfo = (flightNo: string, recordDate: string) => {
  if (flightNo && recordDate) {
    ProduceRecordApi.getRecipeInfo(flightNo, recordDate)
      .then((result) => {
        recipeInfosList.value = result || []
        recipeVisible.value = true
      })
      .catch((err) => {
        console.error('获取餐食信息失败:', err)
        message.error('获取餐食信息失败')
      })
  }
}

/** 列设置 */
interface TableColumn {
  prop: string
  label: string
  width?: number
  editable?: boolean
  editWidth?: number
  type?: string
}

// 统一列定义：新增“航线”列（prop: route，label: 航线，由depLoc-arrLoc拼接）
const allColumns: TableColumn[] = [
  { prop: 'carInfos', label: '排班编号', width: 220, editable: true, editWidth: 180, type: '选择' },
  { prop: 'flightNo', label: '航班号', width: 150, type: '文本' },
  { prop: 'route', label: '航线', width: 180, type: '文本' }, // 新增航线列
  { prop: 'machineNo', label: '机号', width: 150, editable: true, editWidth: 130, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 120, type: '时间' },
  {
    prop: 'preLandingTime',
    label: '预落时间',
    width: 120,
    editable: true,
    editWidth: 120,
    type: '时间'
  },
  {
    prop: 'inboundTime',
    label: '实落时间',
    width: 120,
    editable: true,
    editWidth: 120,
    type: '时间'
  },
  { prop: 'recordDate', label: '日期', width: 150, type: '日期' },
  {
    prop: 'airportStands',
    label: '机位',
    width: 150,
    editable: true,
    editWidth: 130,
    type: '文本'
  },
  { prop: 'airlineComp', label: '航空公司', width: 150, type: '字典' },
  { prop: 'pstatus', label: '生产状态', width: 150, type: '状态' } // 生产状态列
]

// 列设置变量
const columnSettingVisible = ref(false)
const backendColumnSettings = ref<{ prop: string; sort: number; visible?: boolean }[]>([])
const selectedColumnProps = ref<string[]>([])
const selectedColumns = ref<TableColumn[]>([])
const tempSelectedColumnProps = ref<string[]>([])
const tempSelectedColumns = ref<TableColumn[]>([])
const isDragging = ref(false)
const dragIndex = ref(-1)
const dragOverIndex = ref(-1)
const dragStartY = ref(0)
const userList = ref([])

// 从后端获取列配置
const fetchColumnSettings = async () => {
  try {
    const res = await ScheduleRecordApi.getTableitem({ tableType: TABLE_TYPE })
    if (!res?.props?.length) return []
    return res.props
      .filter(
        (setting) =>
          setting?.prop &&
          allColumns.some((col) => col.prop === setting.prop) &&
          setting.visible !== false
      )
      .map((setting) => ({
        prop: setting.prop.trim(),
        sort: typeof setting.sort === 'number' ? setting.sort : 0,
        visible: true
      }))
  } catch (err) {
    console.error('获取列配置失败:', err)
    return []
  }
}

// 初始化列设置
const initColumnSettings = async () => {
  try {
    const backendSettings = await fetchColumnSettings()
    if (backendSettings.length) {
      const sorted = [...backendSettings].sort((a, b) => a.sort - b.sort)
      selectedColumnProps.value = sorted.map((s) => s.prop)
    } else {
      selectedColumnProps.value = allColumns.map((col) => col.prop)
    }
    updateSelectedColumns()
  } catch (err) {
    console.error('初始化列配置失败:', err)
    selectedColumnProps.value = allColumns.map((col) => col.prop)
    updateSelectedColumns()
  }
}

// 更新选中列
const updateSelectedColumns = () => {
  const cols = selectedColumnProps.value
    .map((prop) => allColumns.find((col) => col.prop === prop))
    .filter((col): col is TableColumn => !!col)
  selectedColumns.value = []
  nextTick(() => (selectedColumns.value = cols))
}

// 更新临时选中列
const updateTempSelectedColumns = () => {
  const cols = tempSelectedColumnProps.value
    .map((prop) => allColumns.find((col) => col.prop === prop))
    .filter((col): col is TableColumn => !!col)
  tempSelectedColumns.value = []
  nextTick(() => (tempSelectedColumns.value = cols))
}

// 打开列设置弹窗
const handleOpenColumnSetting = () => {
  tempSelectedColumnProps.value = [...selectedColumnProps.value]
  updateTempSelectedColumns()
  columnSettingVisible.value = true
}

// 保存列设置
const saveColumnSettings = async () => {
  try {
    const data = {
      tableType: TABLE_TYPE,
      props: tempSelectedColumns.value.map((col, idx) => ({
        prop: col.prop,
        label: col.label,
        width: col.width || 150,
        visible: true,
        sort: idx + 1,
        editable: col.editable || false,
        editWidth: col.editWidth || 130,
        type: col.type || '文本'
      }))
    }
    await ScheduleRecordApi.updateTableitem(data)
    selectedColumnProps.value = [...tempSelectedColumnProps.value]
    selectedColumns.value = [...tempSelectedColumns.value]
    message.success('列设置保存成功')
    columnSettingVisible.value = false
  } catch (err) {
    console.error('保存列配置失败:', err)
    message.error('列设置保存失败')
  }
}

// 拖拽逻辑
const startDrag = (index: number, e: MouseEvent) => {
  isDragging.value = true
  dragIndex.value = index
  dragStartY.value = e.clientY
  const onMove = (moveE: MouseEvent) => onDragMove(moveE)
  const onUp = () => stopDrag(onMove, onUp)
  const onLeave = () => stopDrag(onMove, onUp)
  document.addEventListener('mousemove', onMove)
  document.addEventListener('mouseup', onUp)
  document.addEventListener('mouseleave', onLeave)
  e.preventDefault()
}

const onDragMove = (e: MouseEvent) => {
  if (!isDragging.value || dragIndex.value === -1) return
  const item = document.elementFromPoint(e.clientX, e.clientY)?.closest('.draggable-item')
  if (!item) return
  const items = Array.from(document.querySelectorAll('.draggable-item'))
  const currentIdx = items.indexOf(item)
  if (currentIdx === -1 || currentIdx === dragIndex.value) return
  dragOverIndex.value = currentIdx
  if (Math.abs(e.clientY - dragStartY.value) > 20) {
    const newCols = [...tempSelectedColumns.value]
    const [removed] = newCols.splice(dragIndex.value, 1)
    newCols.splice(currentIdx, 0, removed)
    tempSelectedColumns.value = newCols
    tempSelectedColumnProps.value = newCols.map((col) => col.prop)
    dragStartY.value = e.clientY
  }
}

const stopDrag = (moveHandler?: (e: MouseEvent) => void, upHandler?: () => void) => {
  isDragging.value = false
  dragIndex.value = -1
  dragOverIndex.value = -1
  if (moveHandler) document.removeEventListener('mousemove', moveHandler)
  if (upHandler) document.removeEventListener('mouseup', upHandler)
  document.removeEventListener('mouseleave', stopDrag)
}

// 计算属性
const displayedColumns = computed<TableColumn[]>(() => [...selectedColumns.value])
const allColumnsForTransfer = computed(() =>
  allColumns.map((col) => ({ key: col.prop, label: col.label }))
)

// 监听临时列变化
watch(tempSelectedColumnProps, () => updateTempSelectedColumns(), { deep: true })

const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) return '未开始'
  const numStatus = Number(statusValue)
  const matched = pstatusList.find((item) => item.value === numStatus)
  return matched ? matched.label : '未开始'
}

/** 虚拟化表格列配置 */
const tableV2Columns = computed<Column<ScheduleRecordVO>[]>(() => {
  const dynamicColumns = displayedColumns.value.map((column) => ({
    key: column.prop,
    title: column.label,
    dataKey: column.prop,
    width: column.width || 150,
    cellRenderer: ({ cellData, rowData }) => {
      const row = rowData as ScheduleRecordVO
      const isDisabled = row.pstatus === 12
      // 修复3：生产状态列直接使用row.pstatus确保正确取值
      const value =
        column.prop === 'pstatus'
          ? row.pstatus !== undefined
            ? row.pstatus
            : 0
          : cellData?.toString() || ''

      // 新增：航线列渲染（depLoc - arrLoc拼接）
      if (column.prop === 'route') {
        const depLoc = row.depLoc || ''
        const arrLoc = row.arrLoc || ''
        const routeText = depLoc && arrLoc ? `${depLoc} - ${arrLoc}` : '-'
        return (
          <ElTooltip content={routeText} placement="top">
            <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ">
              {routeText}
            </div>
          </ElTooltip>
        )
      }

      // 可编辑列渲染
      if (column.editable) {
        // 排班编号（carInfos对应row.carInfo）
        if (column.prop === 'carInfos') {
          return (
            <ElInput
              modelValue={row.carInfo || ''}
              onUpdate:modelValue={(val) => {
                row.carInfo = val
              }}
              placeholder="请输入车辆信息"
              clearable
              class={`!w-${column.editWidth || 180}px`}
              onBlur={() => handleCarInfoBlur(row)}
              showWordLimit
              disabled={isDisabled} 
            />
          )
        }

        // 时间类型可编辑列
        if (isTimeColumn(column.prop)) {
          return (
            <ElInput
              modelValue={value}
              onUpdate:modelValue={(val) => {
                row[column.prop] = val
              }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 140}px`}
              onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
              onBlur={() => handleColumnTimeBlur(row, column.prop)}
              showWordLimit
              disabled={isDisabled} 
            />
          )
        }

        // 数字类型可编辑列
        if (isNumberColumn(column.prop)) {
          return (
            <ElInput
              modelValue={value}
              onUpdate:modelValue={(val) => {
                row[column.prop] = val
              }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 130}px`}
              onInput={(e) => handleNumberInput(row, column.prop, e.target.value)}
              onBlur={() => handleNumberBlur(row, column.prop)}
              showWordLimit
              type="number"
              min="0"
              disabled={isDisabled} 
            />
          )
        }

        // 普通文本可编辑列
        return (
          <ElInput
            modelValue={value}
            onUpdate:modelValue={(val) => {
              row[column.prop] = val
            }}
            placeholder={`请输入${column.label}`}
            clearable
            class={`!w-${column.editWidth || 130}px`}
            onBlur={() => handleTextBlur(row, column.prop)}
            showWordLimit
            disabled={isDisabled} 
          />
        )
      }

      // 修复4：生产状态列渲染增加类型判断和容错处理
      if (column.prop === 'pstatus') {
        const statusValue = typeof value === 'number' ? value : Number(value)
        const matchedStatus = pstatusList.find((item) => item.value === statusValue)
        return (
          <ElTag type="primary" class="flex items-center justify-center">
            {matchedStatus ? matchedStatus.label : '未开始'}
          </ElTag>
        )
      }

      // 航空公司（字典标签）
      if (column.prop === 'airlineComp') {
        return h(DictTag, {
          type: DICT_TYPE.PPLAN_AIRLINE_ID,
          value: row.airlineComp
        })
      }

      // 时间列（格式化显示）
      if (isTimeColumn(column.prop)) {
        const formatted = formatDisplayTime(value) || '-'
        return <span class="flex items-center">{formatted}</span>
      }

      // 文本列（溢出tooltip）
      if (['flightNo', 'machineNo', 'airportStands', 'recordDate'].includes(column.prop)) {
        // 为航班号添加点击事件
        const handleClick =
          column.prop === 'flightNo' ? () => openShiftInfo(row.carInfo, row.recordDate) : undefined

        return (
          <ElTooltip content={value || '-'} placement="top">
            <div
              class={`overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ${
                column.prop === 'flightNo' ? 'cursor-pointer hover:text-primary' : ''
              }`}
              onClick={handleClick}
            >
              {value || '-'}
              {column.prop === 'flightNo'}
            </div>
          </ElTooltip>
        )
      }
      // 普通列
      return <span class="flex items-center">{value || '-'}</span>
    }
  }))

  // 操作列
  const actionColumn: Column<ScheduleRecordVO> = {
    key: 'operations',
    title: '操作',
    width: 140,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as ScheduleRecordVO
      return (
        <div style="display: flex; align-items: center; justify-center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openRecipeInfo(row.flightNo, row.recordDate)}
          >
            餐食详情
          </ElButton>

          <ElDropdown
            v-slots={{
              dropdown: () => (
                <ElDropdownMenu>
                  {pstatusList.map((item) => (
                    <ElDropdownItem
                      key={item.value}
                      onClick={() => handleStatusChange(row, item.value)}
                    >
                      {item.label}
                    </ElDropdownItem>
                  ))}
                </ElDropdownMenu>
              )
            }}
          >
            <ElButton type="primary" link size="small">
              <ElIcon class="mr-1">
                <DArrowRight />
              </ElIcon>
              更多
            </ElButton>
          </ElDropdown>
        </div>
      )
    }
  }

  return [...dynamicColumns, actionColumn]
})

/** 自动刷新 */
const refreshInterval = ref(120000)
const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)
const autoRefreshEnabled = ref(true)

const startAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
  autoRefreshTimer.value = setInterval(() => getList(), refreshInterval.value)
}

const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
}

/** 初始化 */
onMounted(async () => {
  try {
    await initColumnSettings()
    await nextTick()
    await getList()
    if (autoRefreshEnabled.value) startAutoRefresh()
  } catch (err) {
    console.error('页面初始化失败:', err)
    message.error('页面初始化失败')
  }
})

onUnmounted(() => stopAutoRefresh())

// 行样式
const tableRowClassName = ({ rowData }: { rowData: any }) => {
  return rowData?.markStatus === 1 ? 'row-first' : ''
}
</script>

<style scoped>
:deep(.el-table__row.row-first),
:deep(.el-table-v2__row.row-first) {
  background-color: #f26a6e !important;
}

.draggable-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}
.draggable-item {
  position: relative;
  user-select: none;
  transition: all 0.2s ease;
}
.draggable-item:hover {
  background-color: #f8fafc !important;
  border-color: #c0c4cc !important;
}
.draggable-item .el-icon-rank {
  cursor: grab;
  transition: all 0.2s ease;
}
.draggable-item .el-icon-rank:active {
  cursor: grabbing;
  transform: scale(1.2);
}
.draggable-item .el-icon {
  font-size: 16px;
  transition: all 0.2s ease;
}
.draggable-item .el-icon:hover {
  transform: scale(1.1);
  color: #409eff !important;
}

:deep(.el-table-v2__cell) {
  padding: 4px 12px !important;
  border-bottom: 1px solid #f0f0f0;
}
:deep(.el-table-v2__header) {
  background-color: #f8fafc !important;
  border-bottom: 1px solid #e6e6e6;
}
:deep(.el-table-v2__header-cell) {
  font-weight: 500;
  color: #333;
  padding: 8px 12px !important;
}
:deep(.el-input__inner) {
  width: 100% !important;
  min-height: 32px !important;
}
:deep(.el-input) {
  margin: 0 !important;
}
:deep(.el-table-v2__cell .el-button--text) {
  padding: 4px 8px !important;
}

.overflow-hidden {
  overflow: hidden;
}
.whitespace-nowrap {
  white-space: nowrap;
}
.text-ellipsis {
  text-overflow: ellipsis;
}
</style>
